package com.daxt.utils;

import cn.hutool.core.codec.Base64Decoder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.dic.DicDocFileType;
import com.daxt.model.dic.DicDocPattern;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.model.dto.BaseDocDto;
import com.daxt.model.dto.BaseQueryDto;
import com.daxt.model.service.archives.param.GenCategoryNum;
import com.daxt.model.service.archives.vo.ArchivesBase;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.archives.vo.ArchivesType;
import com.daxt.model.service.archives.vo.ArchivesTypeDoc;
import com.daxt.model.service.base.vo.Dic;
import com.daxt.utils.file.FileBaseUtil;
import com.daxt.utils.file.PdfUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 档案工具类
 *
 * @author: lig
 * @date: 2021-08-19
 */
public class ArchivesUtil {


    /**
     * @description: 档案工具  构造分类号，获取最后的分类号
     *
     * @author: lig
     * @date: 2021/8/11
     */
    public static void builClassNum(ArchivesDoc archivesDoc){
        if(null != archivesDoc && !StringUtils.isEmpty(archivesDoc.getClassNum())){
            archivesDoc.setClassNum(archivesDoc.getClassNum().substring(archivesDoc.getClassNum().lastIndexOf("/")+1));
        }
    }
    /**
     * @description: 档案工具  构造分类号，获取最后的分类号
     *
     * @author: lig
     * @date: 2021/8/11
     */
    public static String builClassNum(String classNum){
        return classNum.substring(classNum.lastIndexOf("/")+1);
    }



    /**
     * @description: 初始化字段
     *
     * @author: lig
     * @date: 2021/8/19
     */
    public static ArchivesTypeDoc initializeArchivesTypeDoc(ArchivesBase archivesBase, ArchivesType entity) {

        ArchivesTypeDoc typeDoc = new ArchivesTypeDoc();
        if (DicDocPattern.PATTERN_1.getKey().equals(entity.getModel())) { //卷
            typeDoc.setExtType(DicDocFileType.DOSSIER.getKey());




        } else if (DicDocPattern.PATTERN_0.getKey().equals(entity.getModel())) { //件
            typeDoc.setExtType(DicDocFileType.DOC.getKey());
        }
//        typeDoc.setId(archivesBase.getId());
        typeDoc.setBaseId(archivesBase.getId());
        typeDoc.setColsize(archivesBase.getColsize());
        typeDoc.setColumnComment(archivesBase.getColumnComment());
        typeDoc.setExtColumn(archivesBase.getExtColumn());
        typeDoc.setDataType(archivesBase.getDataType());
        if (archivesBase.getExtColumn().equals("fondsNum") || archivesBase.getExtColumn().equals("typeNum") || archivesBase.getExtColumn().equals("categoryNum")) {
            typeDoc.setIsEdit("0");
            typeDoc.setIsInsert("0");
            typeDoc.setIsBathEdit("0");
        } else {
            typeDoc.setIsEdit("1");
            typeDoc.setIsInsert("1");
            typeDoc.setIsBathEdit("1");
        }
        typeDoc.setIsImport("1");
        typeDoc.setIsExport("1");
        typeDoc.setIsList("1");
        typeDoc.setIsQuery("1");
        typeDoc.setIsVerify("1");
        typeDoc.setSort(1);
        typeDoc.setTypeId(entity.getId());
        return typeDoc;
    }





    /**
     * @description: 构造文件名（内蒙版）
     * //图片转pdf的文件名按照指定格式《单位名称-年度-卷号-件号（凭证号）》
     * @author: lig
     * @date: 2021/6/10
     */
    public static String builImgToPdfFileName(ArchivesDoc archivesDoc,String unitsName) {
        //单位名称-年度-月份-件号（凭证号）
        StringBuffer buff = new StringBuffer();
//        buff.append(archivesDoc.getTypeNum());//类目号
        buff.append(unitsName);//单位名称
        buff.append("-");
        buff.append(archivesDoc.getArchivalYear());
        buff.append("-");
        buff.append(archivesDoc.getExt20());
        buff.append("-");
        buff.append(archivesDoc.getDossierNum());
        buff.append("-");
        buff.append(archivesDoc.getItemNum());
        //buff.append("(");
        //buff.append(archivesDoc.getPageNum());//页号
        //buff.append(")");

        return buff.toString();
    }


//    /**
//     * @description: 构造文件名称
//     * @author: lig
//     * @date: 2021-07-23
//     */
//    public static String buildFileName(File tempFile, ArchivesDoc doc, String pattern) {
////        String newName = FileBaseUtil.getFileDirName(tempFile);
//        String newName = tempFile.getName();
//        //目录默认追加.pdf
//        if(newName.lastIndexOf(".")<1)newName = newName + ".pdf";
//        String ext = "." + FileBaseUtil.getFileNameExt(newName);
//
//        if (DicDocPattern.PATTERN_0.getKey().equals(pattern)) {
//            newName = doc.getItemNum() + ext;
//        }
//
//        //版本标识 lig  2021-06-10
//        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_2)) {
//            //图片转pdf的文件名按照指定格式《单位名称-年度-卷号-件号（凭证号）》
//            newName = builImgToPdfFileName(doc) + ext;
//        }
//        return newName;
//    }



    /**
     * @description: 构造图片转PDF文件
     * @author: lig
     * @date: 2021/7/23
     */
    public static File builImgToPdfFile(File tempFile, ArchivesDoc archivesDoc, String pattern, String fileName) throws Exception {
        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);
        File saveFile = null;
        String get32uuid = IdWorker.get32UUID();
        String tempFileUrl = tempFile.getAbsolutePath();
        if (tempFile.isDirectory()) {
            File[] listFiles3 = tempFile.listFiles();
            if (listFiles3.length > 0) {
                if (FileBaseUtil.isImg(FileBaseUtil.getFileExtName(listFiles3[0]))) {

                    File file1 = new File(tempFileUrl);
                    String custom = "";
                    if (pattern.equals("0")) {//"0件 1卷
                        custom = archivesDoc.getItemNum();
                    }
                    if (pattern.equals("1")) {//"0件 1卷
                        custom = archivesDoc.getDossierNum();
                    }

                    StringBuffer sb = new StringBuffer();
//                    sb.append(File.separator);
                    sb.append(tempPath);
                    sb.append(get32uuid);
                    sb.append(File.separator);
                    if (!org.springframework.util.StringUtils.isEmpty(custom)) {
                        sb.append(custom);
                        sb.append(File.separator);
                    }


//                    String pdfFileName = fileName.substring(0,fileName.lastIndexOf(".")) + ".pdf";
                    PdfUtils.toPdf(file1.listFiles(), tempFileUrl + File.separator, sb.toString(),
                            FileBaseUtil.getFileNameFront(fileName));
                    saveFile = new File(sb.toString() + fileName);

                }
            }
        }
        return saveFile;
    }




    /**
     * @description: 类目生成
     *
     * @author: lig
     * @date: 2021/9/15
     */
    public static List<GenCategoryNum> genCategoryList(String genCategoryNum, String genCategoryType, Map entity) {
        if (org.springframework.util.StringUtils.isEmpty(genCategoryNum) || org.springframework.util.StringUtils.isEmpty(genCategoryType)) {
            return null;
        }
        String[] splitClass = genCategoryNum.split(genCategoryType);
        List<GenCategoryNum> column = new ArrayList<GenCategoryNum>();
        if (splitClass != null) {
            for (int i = 0; i < splitClass.length; i++) {
                Object object = entity.get(splitClass[i]);
//                if (object != null) {
                    if ("classNum".equals(splitClass[i]) && object.toString().contains("/")) {
                        String[] split = object.toString().split("/");
                        if (split != null && split.length > 0) {
                            for (String string : split) {
                                GenCategoryNum genCategoryNumEntity = new GenCategoryNum();
                                // genCategoryNumEntity.setId(id);
                                genCategoryNumEntity.setColumn(splitClass[i]);
                                genCategoryNumEntity.setValue(string);
                                column.add(genCategoryNumEntity);
                            }
                        }
                    } else {
                        GenCategoryNum genCategoryNumEntity = new GenCategoryNum();
                        // genCategoryNumEntity.setId(id);
                        genCategoryNumEntity.setColumn(splitClass[i]);
                        genCategoryNumEntity.setValue(object == null ? "" : object.toString());
                        column.add(genCategoryNumEntity);
                    }
//                }
            }
        }
        return column;
    }



    /**
     * @description: 查询条件
     *
     * @author: lig
     * @date: 2021/10/12
     */
    public static List<String> queryCondition(String condition){
        List<String> queryCondition = new ArrayList<>();
        if (!StringUtils.isEmpty(condition)) {
            condition = Base64Decoder.decodeStr(condition, Charset.forName("UTF-8"));
        }
        if (!org.springframework.util.StringUtils.isEmpty(condition) && condition.contains(":")) {
            int indexOf = condition.indexOf("aconcata");
            if (indexOf > 0) {
                String[] split = condition.split("aconcata");
                for (String string : split) {
                    if (string.indexOf(":") > 0) {
                        String[] split2 = string.split(":");
                        if (split2[0].equals("base")) {
                            queryCondition.add("a." + split2[1]);
                        } else if (split2[0].equals("ext")) {
                            queryCondition.add("b." + split2[1]);
                        }
                    }
                }
            } else {
                if (condition.indexOf(":") > 0) {
                    String[] split2 = condition.split(":");
                    if (split2[0].equals("base")) {
                        queryCondition.add("a." + split2[1]);
                    } else if (split2[0].equals("b." + split2[1])) {
                        queryCondition.add(condition);
                    }
                }
            }
        }
        return queryCondition;
    }

    public static List<String> conditionToChinese(List<String> queryCondition,List<ArchivesTypeDoc> collect,List<Dic> dicListc){
        List<String> conditionChinese = new ArrayList<>();
        for(String query : queryCondition){
            StringBuffer strBuff = new StringBuffer();
            strBuff.append("【");
            String str = query;
//            String str = "a.dossierNum like '%333%'";
            String a1 = str.substring(0,str.indexOf(" "));

            a1 = a1.replace("a.","");
            a1 = a1.replace("b.","");

            a1 = a1.trim();

//            if(a1.equalsIgnoreCase("storagePeriod"))dicValue = dic.get("storagePeriod");
//            if(a1.equalsIgnoreCase("openState"))dicValue = dic.get("openState");
//            if(a1.equalsIgnoreCase("secret"))dicValue = dic.get("secret");


            String finalA = a1;
            Dic dic = dicListc.stream()
                    .filter(s->s.getDicType().equals(finalA))
//                    .filter(s->s.getExtColumn().equalsIgnoreCase("storePeriod"))
                    .findFirst()
                    .orElse(null);



            ArchivesTypeDoc boys = collect.stream()
                    .filter(s->s.getExtColumn().equals(finalA))
//                    .filter(s->s.getExtColumn().equalsIgnoreCase("storePeriod"))
                    .findFirst()
                    .orElse(null);


            if(null != boys){
                strBuff.append(boys.getColumnComment());
            }

            strBuff.append("、");

            String a2 = str.substring(str.indexOf(" "),str.lastIndexOf(" "));
            a2 = a2.replaceAll("not like","不包含");
            a2 = a2.replaceAll("like","包含");
            a2 = a2.replaceAll("not null","不为空");
            a2 = a2.replaceAll("is null","为空");
            a2 = a2.replaceAll("!=","不等于");
            a2 = a2.replaceAll("=","不等于");
            a2 = a2.trim() + "、";
            strBuff.append(a2);

            String a3 = str.substring(str.lastIndexOf(" "));
            a3 = a3.replaceAll("'%","");
            a3 = a3.replaceAll("%'","");
            a3 = a3.replaceAll("'","");
            a3 = a3.replaceAll("'","");
            a3 = a3.trim();
            if(null != dic){
                List<Dic> dicL = dic.getChildren();
                String finalA3 = a3;
                Dic dicBean = dicL.stream()
                        .filter(s->s.getDicType().equals(finalA3))
//                    .filter(s->s.getExtColumn().equalsIgnoreCase("storePeriod"))
                        .findFirst()
                        .orElse(null);

                a3 = dicBean.getDicValue();

            }
            strBuff.append(a3);
            strBuff.append("】");
            conditionChinese.add(strBuff.toString());
        }
        return conditionChinese;

    }


    /**
     * @description: 构造 档案附件路径
     *
     * @author: lig
     * @date: 2021-11-05
     */
    public static String buildFilePath(ArchivesDoc archivesDoc,String fileName){
        StringBuffer sb = new StringBuffer();
        String u = "/";
//        sb.append(SystemConfig.ossDir);
//        sb.append(u);
        sb.append(archivesDoc.getFondsId());
        sb.append(u);
        sb.append(archivesDoc.getTypeId());
        sb.append(u);
        if(null != archivesDoc.getClassId()){
            sb.append(archivesDoc.getClassId());
            sb.append(u);
        }
        if(!StringUtils.isEmpty(archivesDoc.getFileType())){
            sb.append(archivesDoc.getFileType());
            sb.append(u);
        }
        sb.append(archivesDoc.getId());
        sb.append(u);
        sb.append(fileName);

        return sb.toString();
    }


    /**
     * @description: 构造基础查询
     *
     * @author: lig
     * @date: 2022/2/18
     */
    public static <T> QueryWrapper<T> builBaseQueryWrapper(BaseQueryDto baseQueryDto){
//    public static QueryWrapper<T> builBaseQueryWrapper(QueryWrapper<T> queryWrapper, ArchivesDoc archivesDoc){

        QueryWrapper<T> queryWrapper = new QueryWrapper<T>();

        if(StringUtils.isNotEmpty(baseQueryDto.getFondsId())){
            queryWrapper.eq(BaseConstants.field_fondsId, baseQueryDto.getFondsId());
        }
        if(StringUtils.isNotEmpty(baseQueryDto.getTypeId())){
            queryWrapper.eq(BaseConstants.field_typeId, baseQueryDto.getTypeId());
        }
        if(StringUtils.isNotEmpty(baseQueryDto.getClassId())){
            queryWrapper.eq(BaseConstants.field_classId, baseQueryDto.getClassId());
        }
        return queryWrapper;
    }

    /**
     * @description: 档案校验重复数据
     *
     * @author: lig
     * @date: 2021/12/6
     */
    public static QueryWrapper<ArchivesDoc> verifyRepetition(ArchivesDoc adBean) {
        QueryWrapper<ArchivesDoc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fondsId", adBean.getFondsId());
        queryWrapper.eq("typeId", adBean.getTypeId());
        if (!org.springframework.util.StringUtils.isEmpty(adBean.getId())) {
            queryWrapper.notIn("id", adBean.getId());
        }
        queryWrapper.eq("classId", adBean.getClassId());
        if(StringUtils.isNotEmpty(adBean.getArchivalYear())){
            queryWrapper.eq("archivalYear", adBean.getArchivalYear());
        }
        if(StringUtils.isNotEmpty(adBean.getStoragePeriod())){
            queryWrapper.eq("storagePeriod", adBean.getStoragePeriod());
        }

//        if(RedisUtil.isAppoint(VersionsMarkType.VERSIONS_2)){
//            queryWrapper.eq("classNum", adBean.getClassId());
//        }
        queryWrapper.eq("isDelete", "0");

        queryWrapper.and(Wrapper -> Wrapper.eq("state", "2").or().eq("state", "1").or().eq("state", "0"));

        queryWrapper.eq("fileType", adBean.getFileType());
        if(adBean.getFileType().equals(DicDocFileType.DOSSIER.getKey())){
            queryWrapper.eq("dossierNum", adBean.getDossierNum());
        }
        if(adBean.getFileType().equals(DicDocFileType.DOC.getKey())){
            if(StringUtils.isNotEmpty(adBean.getDossierNum())){
                queryWrapper.eq("dossierNum", adBean.getDossierNum());
            }
            queryWrapper.eq("itemNum", adBean.getItemNum());
        }
        if(adBean.getFileType().equals(DicDocFileType.SCATTERED.getKey())){
            queryWrapper.eq("itemNum", adBean.getItemNum());
        }
        if(adBean.getDossierId()!=null&& adBean.getDossierId()!=0){
            queryWrapper.eq("dossierId", adBean.getDossierId());
        }
        return queryWrapper;

    }

    /**
     * @description: 构造档案基础信息
     *
     * @author: lig
     * @date: 2021-12-14
     */
    public static BaseDocDto buildBaseDoc(ArchivesDoc adBean) {
        BaseDocDto base = new BaseDocDto();
        BeanUtils.copyProperties(adBean,base);
//        base.setArchivalNum(adBean.getArchivalNum());
//        base.setFileType(adBean.getFileType());

        return base;

    }

    /**
     * @description: 构造文档 ids
     *
     * @author: lig
     * @date: 2022/2/28
     */
    public static List<Long> buildDocIds(List<ArchivesDoc> list) {
        List<Long> ids = new ArrayList();
        list.forEach((ArchivesDoc doc)->{
            ids.add(doc.getId());

        });

        return ids;

    }

    /**
     * 比较档案哪些字段的值发生了变换
     * @param oldArchives 旧数据
     * @param newArchives 新数据
     * @return 变化的结果
     */
    public static String compareArchives(ArchivesDoc oldArchives,ArchivesDoc newArchives,Map<String,String> archivesTypeDocMap){
        StringBuilder str=new StringBuilder();
        try {
            Class<?> clazz = oldArchives.getClass();
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    String fieldName = field.getName();

                    // 设置字段为可访问状态
                    field.setAccessible(true);

                    // 获取字段值并打印
                    String docName = archivesTypeDocMap.get(fieldName);
                    if(docName != null && !filterField(fieldName) ){

                        String oldValue=field.get(oldArchives)+"";
                        String newValue=field.get(newArchives)+"";

                        oldValue = oldValue==null || "".equals(oldValue) || "null".equals(oldValue) ? "空":oldValue;
                        newValue = newValue==null || "".equals(newValue) || "null".equals(newValue) ? "空":newValue;

                        if(!oldValue.equals(newValue)){
                            str.append(docName).append("：从“").append(oldValue).append("”修改改为“").append(newValue).append("”；");
                        }
                    }
                }
            }
        }catch (IllegalAccessException e){
            e.printStackTrace();
            return null;
        }
        return str.toString();
    }

    private static boolean filterField(String fieldName) {
        if(fieldName.equals("fondsNum")) return true;
        if(fieldName.equals("fondsName")) return true;
        if(fieldName.equals("typeNum")) return true;
        if(fieldName.equals("typeName")) return true;
        if(fieldName.equals("classNum")) return true;
        if(fieldName.equals("className")) return true;
        if(fieldName.equals("parentClassName")) return true;
        if(fieldName.equals("classTreeStr")) return true;
        if(fieldName.equals("isFile")) return true;
        if(fieldName.equals("identType")) return true;
        if(fieldName.equals("startYear")) return true;
        if(fieldName.equals("startMonth")) return true;
        if(fieldName.equals("startDay")) return true;
        if(fieldName.equals("endYear")) return true;
        if(fieldName.equals("endMonth")) return true;
        if(fieldName.equals("endDay")) return true;
        if(fieldName.equals("fourTest")) return true;
        if(fieldName.equals("fourResult")) return true;
        if(fieldName.equals("docName")) return true;
        if(fieldName.equals("docPath")) return true;
        if(fieldName.equals("lmId")) return true;
        if(fieldName.equals("mountPage")) return true;
        if(fieldName.equals("remainDay")) return true;

        return false;
    }



    /*public static void main(String[] args){

        String end = "2021-12-24";
        String cruu = "2021-12-14";

        System.out.println("222222:"+cruu.compareTo(end));




//        StringBuffer strBuff = new StringBuffer();
//        String str = "a.dossierNum like '%333%'";
//        String a1 = str.substring(0,str.indexOf(" "));
//        a1 = a1.replaceAll("a.","");
//        a1 = a1.replaceAll("b.","");
//
//        a1 = a1.trim() + "、";
//        strBuff.append(a1);
//
////        包含  in
////        不包含  not in
////                等于  =
////                不等于  !=
////                        为空  is null
////        不为空 not null
//        String a2 = str.substring(str.indexOf(" "),str.lastIndexOf(" "));
//        a2 = a2.replaceAll("not like","不包含");
//        a2 = a2.replaceAll("like","包含");
//        a2 = a2.replaceAll("not null","不为空");
//        a2 = a2.replaceAll("null","为空");
//        a2 = a2.replaceAll("!=","不等于");
//        a2 = a2.replaceAll("=","不等于");
//        a2 = a2.trim() + "、";
//        strBuff.append(a2);
//
//        String a3 = str.substring(str.lastIndexOf(" "));
//        a3 = a3.replaceAll("'%","");
//        a3 = a3.replaceAll("%'","");
//        a3 = a3.trim();
//        strBuff.append(a3);
//
//
//        System.out.println(strBuff.toString());

    }*/
}
